package com.liuyi.netty.mqtt.processed.store;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mqtt channel 通道储存接口
 * 功能
 * - 储存 clientId和Channel 的关系
 */
public class MqttChannelManage {

    private final static Map</* ClientId */String, MqttChannel> STORE = new ConcurrentHashMap<>();

    private final static AttributeKey<String> CLIENT_KEY = AttributeKey.valueOf("clientId");

    public static String getClientId(ChannelHandlerContext context){
        Attribute<String> clientAttr = context.channel().attr(CLIENT_KEY);
        return clientAttr.get();
    }

    public static void set(String clientId, ChannelHandlerContext context) {
        Attribute<String> clientAttr = context.channel().attr(CLIENT_KEY);
        clientAttr.set(clientId);
        STORE.put(clientId, new MqttChannel(clientId, context));
    }

    /**
     * 根据clientId查询通道
     */
    public static MqttChannel get(String clientId) {
        return STORE.get(clientId);
    }


    /**
     * remove channel
     */
    private static void remove(String clientId) {
        STORE.remove(clientId);
    }

    /**
     * close channel
     */
    public static void close(String clientId) {
        final MqttChannel channel = get(clientId);
        if (channel != null) {
            channel.getChannel().close();
        }
        remove(clientId);
    }
}
